/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.wsinfra.deployment.axis.wse.test;

import java.util.Calendar;

import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.xmlbeans.XmlCursor;

import cgl.narada.wsinfra.WsMessageFlow;
import cgl.narada.wsinfra.exception.DeploymentException;
import cgl.narada.wsinfra.exception.MessageFlowException;
import cgl.narada.wsinfra.exception.ProcessingException;
import cgl.narada.wsinfra.exception.WsFaultException;
import cgl.narada.wsinfra.schemas.addressing.EndpointReferenceType;
import cgl.narada.wsinfra.schemas.addressing.FromDocument;
import cgl.narada.wsinfra.schemas.eventing.DeliveryType;
import cgl.narada.wsinfra.schemas.eventing.FilterType;
import cgl.narada.wsinfra.schemas.eventing.GetStatusDocument;
import cgl.narada.wsinfra.schemas.eventing.IdentifierDocument;
import cgl.narada.wsinfra.schemas.eventing.RenewDocument;
import cgl.narada.wsinfra.schemas.eventing.SubscribeDocument;
import cgl.narada.wsinfra.schemas.soap.EnvelopeDocument;
import cgl.narada.wsinfra.util.SoapEnvelopeConversion;
import cgl.narada.wsinfra.util.SoapMessageAlteration;
import cgl.narada.wsinfra.wsa.WsaEnvelopeCreator;
import cgl.narada.wsinfra.wsa.WsaEprCreator;
import cgl.narada.wsinfra.wsa.WsaProcessingFactory;
import cgl.narada.wsinfra.wse.WseElementCreation;
import cgl.narada.wsinfra.wse.WseNodeUtils;
import cgl.narada.wsinfra.wse.WseProcessingFactory;
import cgl.narada.wsinfra.wse.WseRequestCreator;
import cgl.narada.wsinfra.wse.impl.WseSinkProcessor;
import cgl.narada.wsinfra.wse.matching.SubscriptionValidator;

/**
 * @author Damodar Yemme
 * Created on Mar 15, 2005
 * This class will help Client to create request to call AxisSink Service.
 *
 */
public class WseSinkClientTestService
    implements WsMessageFlow {
  private String moduleName = "WseSinkClientHandler";

  private WsaEprCreator eprCreator;
  private WseSinkProcessor wseSinkProcessor;
  private EndpointReferenceType sinkEpr;
  private WsaEprCreator wsaEprCreator;
  private WsaEnvelopeCreator wsaEnvelopeCreator;
  private WseRequestCreator wseRequestCreator;
  private WseElementCreation wseElementCreation;
  private static String sinkAddress = WseServicesTestFactory.getSinkAddress();
  private static String smAddress =
      WseServicesTestFactory.getSubscriptionManagerAddress();
  private static WseSinkClientTestService instance =
      new WseSinkClientTestService();
  private EndpointReferenceType subcriptionManagerEpr;
  private SoapMessageAlteration soapMessageAlteration;
  private WseNodeUtils wseNodeUtils;
  /**
   * Default constructor for WseSinkTestHandler class.
   *
   */
  private WseSinkClientTestService() {
    eprCreator = WsaProcessingFactory.getWsaEprCreator();
    sinkEpr = eprCreator.createEpr(sinkAddress);
    soapMessageAlteration = SoapMessageAlteration.getInstance();
    wseSinkProcessor = WseSinkProcessor.getInstance();
    wseNodeUtils = WseProcessingFactory.getWseNodeUtils();
    try {
      wseSinkProcessor.setMessageFlow(this);
    }
    catch (DeploymentException dx) {}
    wseSinkProcessor.setSinkEPR(sinkEpr);
    wsaEprCreator = WsaProcessingFactory.getWsaEprCreator();
    subcriptionManagerEpr = wsaEprCreator.createEpr(smAddress);
    wsaEnvelopeCreator = WsaProcessingFactory.getWsaEnvelopeCreator();
    wseRequestCreator = WseProcessingFactory.getWseRequestCreator();
    wseElementCreation = WseProcessingFactory.getWseElementCreation();
  }

  /**
   * This will return instance of Sink Processor
   * @return WseSinkProcessor
   */
  public WseSinkProcessor getProcessor() {
    return wseSinkProcessor;
  }

  /**
   * This will return WseSinkClientTestService instance
   * @return WseSinkClientTestService
   */
  public static WseSinkClientTestService getInstance() {
    return instance;
  }

  /**
   * Routes a message enroute to the application. The message is basically
   * routed to a neighboring filter which is nearer to the application.
   */
  public final void enrouteToApplication(SOAPMessage soapMessage) throws
      MessageFlowException {
  }

  /**
   * This will enroute Message to Network.This it will call Sink web services.
   * @param SOAPMessage
   * @throws MessageFlowException
   */
  public void enrouteToNetwork(SOAPMessage soapMessage) throws
      MessageFlowException {
    try {
      org.apache.axis.message.SOAPEnvelope senv = (
          org.apache.axis.message.SOAPEnvelope) soapMessage
          .getSOAPPart().getEnvelope();
      System.out.println(moduleName + " soapMessage \n*********\n" + senv);
      Service service = new Service();
      Call call = (Call) service.createCall();
      call.setTargetEndpointAddress(sinkAddress);
      call.setSOAPActionURI("processMessage");
      SOAPEnvelope env = (SOAPEnvelope) call.invoke(senv);
    }
    catch (Exception e) {
      System.out.println(moduleName + " Exception here " + e);
    }
  }

  /**
   *
   * @param subscriptionIdentifier
   * @throws ProcessingException
   * @throws DeploymentException
   * @throws SOAPException
   * @throws MessageFlowException
   */
  public void issueGetStatusRequest(String subscriptionIdentifier) throws
      ProcessingException, DeploymentException, SOAPException,
      MessageFlowException {
    wseSinkProcessor = getProcessor();

    WsaEprCreator wsaEprCreator = WsaProcessingFactory.getWsaEprCreator();

    EndpointReferenceType sinkEpr = wsaEprCreator
        .createEpr(sinkAddress);

    GetStatusDocument getStatusDocument =
        wseElementCreation.newGetStatusDocument();

    EnvelopeDocument envelopeDocument =
        wseRequestCreator.createGetStatus(subcriptionManagerEpr, sinkEpr,
                                          getStatusDocument);
    // Add Identifier to EnvelopeDocument Headers
    IdentifierDocument identifierDocument =
        IdentifierDocument.Factory.newInstance();
    identifierDocument.setIdentifier(subscriptionIdentifier);
    soapMessageAlteration.addToSoapHeaderAsLastChild(envelopeDocument,
        identifierDocument);

    SOAPMessage soapMessage = getSOAPMessage(envelopeDocument);
    System.out.println("Document Generated is " + envelopeDocument);

    IdentifierDocument idDocument = null;
    try {
      idDocument = wseNodeUtils.getIdentifierDocument(envelopeDocument);
    }
    catch (WsFaultException ex) {
      throw new ProcessingException(moduleName + "Unable to process. " +
                                    "Problems related to IdentifierDocument");
    }
    String subscriptionId = idDocument.getIdentifier();
    System.out.println(" subscription Id  :" + subscriptionId);

    enrouteToNetwork(soapMessage);
  }

  /**
   *
   * @param subscriptionIdentifier
   * @param Calender expiresAt
   * @throws ProcessingException
   * @throws MessageFlowException
   */
  public void issueRenewRequest(String subscriptionIdentifier,
                                Calendar expiresAt) throws ProcessingException,
      MessageFlowException {
    RenewDocument renewDocument = wseElementCreation.newRenewDocument(
        expiresAt);

    EnvelopeDocument envelopeDocument =
        wseRequestCreator.createRenew(subcriptionManagerEpr, sinkEpr,
                                      renewDocument);
    // Add Identifier to EnvelopeDocument Headers
    IdentifierDocument identifierDocument =
        IdentifierDocument.Factory.newInstance();
    identifierDocument.setIdentifier(subscriptionIdentifier);
    soapMessageAlteration.addToSoapHeaderAsLastChild(envelopeDocument,
        identifierDocument);

    String report = moduleName + "The CREATED Renew Request is\n" +
        envelopeDocument.toString();
    System.out.println(report);
    SOAPMessage soapMessage = getSOAPMessage(envelopeDocument);

    enrouteToNetwork(soapMessage);
  }

  /**
   *
   * @param subscriptionIdentifier
   * @throws ProcessingException
   * @throws MessageFlowException
   */
  public void issueUnsubscribeRequest(String subscriptionIdentifier) throws
      ProcessingException, MessageFlowException {

    EnvelopeDocument envelopeDocument =
        wseRequestCreator.createUnsubscribe(subcriptionManagerEpr, sinkEpr);

    // Add Identifier to EnvelopeDocument Headers
    IdentifierDocument identifierDocument =
        IdentifierDocument.Factory.newInstance();
    identifierDocument.setIdentifier(subscriptionIdentifier);
    soapMessageAlteration.addToSoapHeaderAsLastChild(envelopeDocument,
        identifierDocument);
    String report = moduleName + "The CREATED Unsubscribe Request is\n"
        + envelopeDocument.toString();
    System.out.println(report);
    SOAPMessage soapMessage = getSOAPMessage(envelopeDocument);
    enrouteToNetwork(soapMessage);
  }

  /**
   *
   * @param sourceAdd
   * @param topic
   * @throws DeploymentException
   * @throws ProcessingException
   * @throws MessageFlowException
   * @throws SOAPException
   */
  public void createSubRequest(String sourceAdd, String topic) throws
      DeploymentException, ProcessingException,
      MessageFlowException, SOAPException {

    WsaEprCreator wsaEprCreator = WsaProcessingFactory.getWsaEprCreator();

    String sourceAddress = sourceAdd;
    EndpointReferenceType sourceEpr = wsaEprCreator
        .createEpr(sourceAddress);
    String deliveryMode =
        "http://schemas.xmlsoap.org/ws/2004/08/eventing/DeliveryModes/Push";
    String topicFilterDialect =
        "http://www.naradabrokering.org/TopicMatching";
    String regExFilterDialect =
        "http://www.naradabrokering.org/RegularExpressionMatching";

    String xpathFilterDialect =
        "http://www.w3.org/TR/1999/REC-xpath-19991116";
    String xqueryFilterDialect =
        "http://www.w3.org/TR/2004/WD-xquery-20041029";
    String topicFilterConstraint = "/Literature/Shakespere";
    String regExFilterConstraint =
        "[Tt]he [Qq]uick [Bb]rown [Ff]ox [Jj]umps";

    String xpathFilterConstraint =
        "declare namespace c1='http://www.naradabrokering.org/catalog'"
        + "$this//c1:catalog/c1:cd/c1:price > 20";

    String nsText = "declare namespace po = 'http://openuri.org/easypo'";
    String pathText = "$this//po:purchase-order/po:line-item";
    // [po:price <= 20.00]";
    String queryText = nsText + pathText;
    String xqueryFilterConstraint = queryText;

    String filterConstraint = topicFilterConstraint;
    String filterDialect = topicFilterDialect;
    String subscriptionType = "";
    String widget = topic;
    if (widget.startsWith("t")) {
      subscriptionType = "topic";
    }
    if (widget.startsWith("x")) {
      subscriptionType = "xpath";
    }
    if (widget.startsWith("r")) {
      subscriptionType = "regex";
    }
    if (widget.startsWith("q")) {
      subscriptionType = "xquery";
    }
    if (subscriptionType.equals("topic")) {
      filterConstraint = topicFilterConstraint;
      filterDialect = topicFilterDialect;
    }

    if (subscriptionType.equals("regex")) {
      filterConstraint = regExFilterConstraint;
      filterDialect = regExFilterDialect;
    }

    if (subscriptionType.equals("xpath")) {
      filterConstraint = xpathFilterConstraint;
      filterDialect = xpathFilterDialect;
    }

    if (subscriptionType.equals("xquery")) {
      filterConstraint = xqueryFilterConstraint;
      filterDialect = xqueryFilterDialect;
    }

    EndpointReferenceType sinkEpr = wsaEprCreator.createEpr(sinkAddress);
    EndpointReferenceType endTo = wsaEprCreator.createEpr(sinkAddress);
    Calendar expiresAt = Calendar.getInstance();
    expiresAt.add(Calendar.MONTH, 1);

    wseSinkProcessor = getProcessor();
    EnvelopeDocument envelopeDocument = wseSinkProcessor
        .createSubscribeRequest(sourceEpr, deliveryMode, endTo,
                                filterDialect, filterConstraint, expiresAt);
    String report = "Message Client The CREATED Subscription Request is\n"
        + envelopeDocument.toString();
    System.out.println(report);
    SOAPMessage soapMessage = getSOAPMessage(envelopeDocument);

    try {
      SubscribeDocument subscribeDocument =
          wseNodeUtils.getSubscribeDocument(envelopeDocument);
      SubscribeDocument.Subscribe subscribe =
          subscribeDocument.getSubscribe();
      FilterType filter = subscribe.getFilter();
      SubscriptionValidator subscriptionValidator =
          SubscriptionValidator.getInstance();
      XmlCursor filterCursor = filter.newCursor();
      String dialect = filter.getDialect();
      String constraint = filterCursor.getTextValue();
      Object expiry = subscribe.getExpires();
      Calendar expiresAtTemp = (Calendar) expiry;
      DeliveryType delivery = subscribe.getDelivery();
      String mode = delivery.getMode();
      System.out.println("Expires At " + expiresAtTemp);
      System.out.println("My dialect " + dialect);
      System.out.println("My constraint " + constraint);
      System.out.println("My Delivery Mode " + mode);
    }
    catch (Exception ex) {
      System.out.println("Exception here" + ex);
    }

    enrouteToNetwork(soapMessage);
  }

  /**
   *
   * @param envelopeDocument
   * @return
   */
  private SOAPMessage getSOAPMessage(EnvelopeDocument envelopeDocument) {
    SOAPMessage soapMessage = null;
    SoapEnvelopeConversion soapEnvelopeConversion = SoapEnvelopeConversion
        .getInstance();
    try {

      soapMessage = soapEnvelopeConversion
          .getSOAPMessage(envelopeDocument);
    }
    catch (ProcessingException ex) {
      String errorReport = "Problems converting to javax.xml.SOAPMessage\n"
          + ex.toString();
      System.out.println(errorReport);
    }

    return soapMessage;
  }

  /**
   *
   * @param source
   * @return
   */
  public SOAPMessage createSOAPMessage(String source) {
    if (source == null) {
      System.out.println(moduleName + "Specified SourceAddress is NULL!");
      return null;
    }
    EndpointReferenceType sourceEpr = wsaEprCreator.createEpr(source);
    FromDocument from = FromDocument.Factory.newInstance();
    EnvelopeDocument envelopeDocument =
        wsaEnvelopeCreator.createSoapEnvelope(from);

    return getSOAPMessage(envelopeDocument);
  }
}